package wt.hpad.activity.main;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import wt.hpad.R;
import wt.hpad.activity.detail.DetailActivity;
import wt.hpad.activity.order.OrderActivity;
import wt.hpad.base.BaseFragment;
import wt.hpad.model.adapter.TableAdapter;
import wt.hpad.model.bean.DishDetail;
import wt.hpad.model.bean.TableInfo;

/**
 * Created by wt on 12.20.
 */

public class MainFragment extends BaseFragment implements MainContract.View {
    MainContract.Presenter mMainPresenter;
    @BindView(R.id.gv_table)
    GridView gvTable;
    Unbinder unbinder;

    public MainFragment() {
    }

    @Override
    public void setPresenter(MainContract.Presenter presenter) {
        mMainPresenter = presenter;
    }


    @Override
    public void closeCurrentActivity() {
        baseActivity.finish();
    }

    @Override
    public void refreshTable(final TableAdapter adapter, final boolean isUpdate, final List<TableInfo> datas) {
        baseActivity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                gvTable.setAdapter(adapter);
            }
        });
    }


    @Override
    public View initViews() {
        View inflate = View.inflate(baseActivity, R.layout.main_frag, null);
        unbinder = ButterKnife.bind(this, inflate);
        return inflate;
    }

    @Override
    public void initData() {
        mMainPresenter.subscribe();

        gvTable.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                // 进入桌台
                mMainPresenter.enterTable(position);
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        // 从各种状态/界面回到主界面时
        // 刷新桌台状态
        mMainPresenter.refreshTableState();
    }

    @Override
    public void startDetailActivity(ArrayList<DishDetail> dishDetails) {
        Intent intent = new Intent(baseActivity, DetailActivity.class);
        Bundle bundle = new Bundle();
        bundle.putParcelableArrayList("dishs", dishDetails);
        intent.putExtras(bundle);
        startActivity(intent);
    }

    @Override
    public void startOrderActivity() {
        startActivity(new Intent(baseActivity, OrderActivity.class));
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }
}
